import { AxiosRequestConfig } from 'axios'
import { SketionRequestOptions } from 'sketion-http'

export interface MyRequest extends SketionRequestOptions, AxiosRequestConfig {
  url: string
  data?: any
}

export class MyResponse<T = any> {
  public code: number

  public msg: string

  public data: T

  public _originalData_: any

  public _customCheckEmpty: ((data: any) => boolean) | undefined

  constructor(code: number, msg: string, data: T, originalData: any, customCheckEmpty?: (data: any) => boolean) {
    this.code = code
    this.msg = msg
    this.data = data
    this._originalData_ = originalData
    this._customCheckEmpty = customCheckEmpty
  }

  public isLoading() {
    return this.code === -100
  }

  public get success() {
    return this.code === 0
  }

  public isEmpty = () => {
    if (this._customCheckEmpty) {
      return this._customCheckEmpty(this.data)
    }
    if (this.data instanceof Array) {
      return this.data.length === 0
    }
    return !this.data
  }

  public setEmpty(): MyResponse<T> {
    this.data = null as any
    return this
  }

  public setError(err: string): MyResponse<T> {
    this.code = 500
    this.msg = err
    return this
  }

  public setLoading(data?: any): MyResponse<T> {
    this.code = -100
    if (data) {
      this.data = data
    }
    return this
  }

  public setSuccess(data?: any): MyResponse<T> {
    this.code = 0
    this.data = data
    return this
  }

  public update(newRes: MyResponse<T>): MyResponse<T> {
    const newMyRes = newRes as MyResponse<T>
    this.code = newMyRes.code
    this.data = newMyRes.data
    this.msg = newMyRes.msg
    this._originalData_ = newMyRes._originalData_
    return this
  }
}
